package com.example.video.conf;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.video.Enum.Language;
import com.example.video.Enum.videoStatus;
import com.example.video.common.Result;
import com.example.video.controller.AdminController;
import com.example.video.entity.Account;
import com.example.video.entity.Video;
import com.example.video.service.impl.AccountServiceImpl;
import com.example.video.service.impl.VideoServiceImpl;
import com.example.video.util.HHdata;
import com.example.video.util.download.DownTask;
import com.example.video.util.queue.DownQueueManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@EnableScheduling
public class ScheduledTasks {

    @Resource
    private AccountServiceImpl accountService;
    @Resource
    private VideoServiceImpl videoService;
    @Resource
    private DownTask downTask;
    @Resource
    private HHdata hHdata;

    @Resource
    private com.example.video.util.translateUtil translateUtil;
    @Resource
    private DownQueueManager downQueueManager;
    @Resource
    private AdminController adminController;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * 定时任务，每天20点执行检索数据
     */
    @Scheduled(cron = "55 06 15 * * ?")
    public void reportCurrentTime() {
//        log.info(" ScheduledTasks -> reporttCurrentTime -> msg : ");
        int page = 1;
        int size = 50;
        List<Account> list = new ArrayList<>();
        list = accountService.getList(page, size);

        // 进行下载下载失败的资源，对于重复的cursor只进行一次扫描
        List<Video> videos = videoService.getListByNotDownLoading();
        Map<String, Video> result = new HashMap<>();
        for (Video video :
                videos) {
            String key = video.getErrCursor() + "-" + video.getAccountId();
            result.put(key, video);
        }
        for (Map.Entry<String, Video> entry : result.entrySet()) {
            Video video = entry.getValue();

            Account account = accountService.getItem(video.getAccountId());
            String errCursor = video.getErrCursor();
            downQueueManager.addTask(account, errCursor);
        }

        // 查看是否发布新视频
        while (!list.isEmpty()) {
            // 直接执行爬数据的bean，在此bean中能直接将未有的视频加入到数据库中并下载，故这里无需再进行其他操作
            for (Account account : list) {
                adminController.freshCrawlData(account.getId());

                // 5.5 注释直接使用AdminController -> freshCrawlData函数
                downQueueManager.addTask(account, null);
            }
            page++;
            list = accountService.getList(page, size);
        }

    }

    /**
     * 每日24点定时，将处理完成的视频状态修改为可上传状态，并翻译其文本，保存倒outeraccount的title字段中
     *
     * @TODO :添加权限
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void changeVideoStatus() {
        // 获取处理完毕的资源
        List<Account> accounts = Db.lambdaQuery(Account.class)
                .select(Account::getId, Account::getLanguage, Account::getToLanguage)
                .list();
        // 遍历每个账户
        accounts.forEach(account -> {
            Integer accountId = account.getId();
            String language = Language.getCodeByName(account.getLanguage());
            String toLanguage = Language.getCodeByName(account.getToLanguage());
            // 获取账户下所有处理完毕的视频
            List<Video> list = Db.lambdaQuery(Video.class)
                    .select(Video::getTitle, Video::getId)
                    .eq(Video::getAccountId, accountId)
                    .eq(Video::getStatus, videoStatus.PROCESSED.getStatus())
                    .list();
            log.info("ScheduledTask -> change ->msg:videoList = " + list);
            // 遍历每个资源
            list.forEach(video -> {

                log.info("ScheduledTask -> change ->msg:video = " + video);
                Result<String> rs = translateUtil.getTransResult(video.getTitle(), language, toLanguage);


               if(rs.getCode() == 0){
                   log.info("ScheduledTask -> change ->msg:翻译成功！翻译结果 = " + rs.getData());
                   // 修改视频状态
                   Db.lambdaUpdate(Video.class)
                           .eq(Video::getId, video.getId())
                           .set(Video::getStatus, videoStatus.UPLOADABLE.getStatus())
                           .set(Video::getTranslateTitle, rs.getData())
                           .update();
               }else{
                   log.info("ScheduledTask -> change ->msg:此文本翻译出错！ = " + video.getTitle());
               }

            });
        });

    }
}
